from cold_start_analyzer.base_analyzer import BaseAnalyzer
from cold_start_analyzer.consts import NOT_AVAILABLE
from cold_start_analyzer import db_helper
from cold_start_analyzer.log_helper import dlog
class Phase1All(BaseAnalyzer):
    description = "Touch事件分发:从第一个Touch事件到MainThread启动"
    """
    起点: 第一个 touch event
    终点: app_thread
    H:void OHOS::AppExecFwk::MainThread::HandleLaunchApplication 开始
    """
    def get_result(self):
        res = db_helper.get_function_cost(self.cursor, 'H:void OHOS::AppExecFwk::MainThread::HandleLaunchApplication', thread_name=self.thread_name)
        if not res:
            dlog.error(f"query_function_cost failed: {self.thread_name}, res: {res}")
            return NOT_AVAILABLE  
        touchTests = db_helper.get_function_cost(self.cursor, "H:TouchTest", 0, res[0][0], thread_name='com.ohos.sceneboard')
        if not touchTests:
            touchTests = db_helper.get_function_cost(self.cursor, "H:TouchTest", 0, res[0][0])
        touchTests = sorted(touchTests, key=lambda x: x[0], reverse=True)
        if not touchTests:
            dlog.error(f"query_function_cost failed: {self.thread_name}, touchTests: {touchTests}")
            return NOT_AVAILABLE
        touchTest = touchTests[0]
        if not touchTest:
            dlog.error(f"query_function_cost failed: {self.thread_name}, touchTest: {touchTest}")
            return NOT_AVAILABLE
        touchEvent = db_helper.get_last_touch_event(self.cursor, 0, touchTest[0])
        if not touchEvent:
            dlog.error(f"query_function_cost failed: {self.thread_name}, touchEvent: {touchEvent}")
            return NOT_AVAILABLE
        self.context[self.__class__.__name__] = {
            'start_ts': touchEvent[0],
            'first_touch': touchEvent[0],
            'touch_test': touchTest[0],
            'end_ts': res[0][0],
        }
        return res[0][0] - touchEvent[0]
    
